package com.frxuexi.reprot

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch

class ReportViewModel:ViewModel() {

    val reportRepository by lazy { ReportRepository() }

    val channel =Channel<ReportIntent>(Channel.UNLIMITED)

    private var _reportState=MutableStateFlow<ReportState>(ReportState.onLoading)
    val reportState:StateFlow<ReportState>
        get() = _reportState

    init {
        viewModelScope.launch {
            channel.consumeAsFlow().collect{
                when(it){
                    is ReportIntent.getReport->{
                        getReport(it.map)
                    }
                    is ReportIntent.commitReport->{
                        commitReport(it.map)
                    }
                    else->{}
                }
            }
        }

    }

    private fun commitReport(map: Map<String, Any>) {
        viewModelScope.launch {
            reportRepository.commitReport(map)
                .flowOn(Dispatchers.IO)
                .catch {
                    it.printStackTrace()
                }.collect{
                    if(it.statusCode==200){
                        _reportState.value=ReportState.onCommitSuccess
                    }else{
                        _reportState.value=ReportState.onError(it.msg!!)
                    }
                }
        }
    }

    private fun getReport(map: Map<String, Int>) {
        viewModelScope.launch {
            reportRepository.getReport(map)
                .flowOn(Dispatchers.IO)
                .catch {
                    it.printStackTrace()
                }.collect{
                    if(it.statusCode==200){
                        _reportState.value=ReportState.oGetSuccess(it.datas)
                    }else{
                        _reportState.value=ReportState.onError(it.msg!!)
                    }
                }
        }
    }
}